from models import Session, User
import json
from datetime import datetime

def view_users():
    session = Session()
    try:
        users = session.query(User).all()
        if not users:
            print("数据库中没有用户记录")
            return
        
        print("\n当前用户列表：")
        print("-" * 50)
        print(f"{'ID':<5} {'用户名':<15} {'创建时间':<20}")
        print("-" * 50)
        
        for user in users:
            created_time = user.created_at.strftime('%Y-%m-%d %H:%M:%S')
            print(f"{user.id:<5} {user.username:<15} {created_time:<20}")
            
    except Exception as e:
        print(f"查看数据库时发生错误: {str(e)}")
    finally:
        session.close()

def add_test_user():
    session = Session()
    try:
        # 检查是否已存在测试用户
        test_user = session.query(User).filter_by(username='test').first()
        if test_user:
            print("测试用户已存在")
            return
            
        # 创建测试用户
        new_user = User(username='test', password='test123')
        session.add(new_user)
        session.commit()
        print("测试用户添加成功")
        
    except Exception as e:
        print(f"添加测试用户时发生错误: {str(e)}")
        session.rollback()
    finally:
        session.close()

if __name__ == '__main__':
    while True:
        print("\n数据库管理工具")
        print("1. 查看所有用户")
        print("2. 添加测试用户")
        print("3. 退出")
        
        choice = input("\n请选择操作 (1-3): ")
        
        if choice == '1':
            view_users()
        elif choice == '2':
            add_test_user()
        elif choice == '3':
            break
        else:
            print("无效的选择，请重试") 